function [Ri Vi Wi] = SIGEconverge(draws,bat,kk)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%This is part of the set of files that accompany the article:       %
%Mankiw, N. Gregory and Ricardo Reis (2007) "Sticky Information in  %
%General Equilibrium," Journal of the European Economic Association,%
%forthcoming. See the appendix of the NBER or CEPR working paper    %
%versions for a detailed explanation of the algorithms.             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Please cite if you use the programs. I do not provide tech support.%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Last revised: August 30, 2006                                      %
%Written by: Ricardo Reis                                           %
%Input: draws, number of batches to split, number of parameters     %
%Output: R, V and W convergenece diagnostics of Brooks-Gellman      %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%n is size of sample, m the number of samples, bat the number of bacthes,
%b the length of each batch
bat=floor(bat); [n temp]=size(draws); m=temp/kk; b=n/bat;
W=zeros(kk*bat,kk*bat); Bn=zeros(kk*bat,kk*bat); V=zeros(kk*bat,kk*bat);
for j=1:bat
    draws_bat=draws(1:b*j,:);
    Wtemp=0;
    for i=1:m
        series=draws_bat(:,kk*(i-1)+1:kk*i);
        s2=cov(series); Wtemp=Wtemp+s2;
        mu(i,:)=mean(series);
    end
    W(kk*(j-1)+1:kk*j,kk*(j-1)+1:kk*j)=Wtemp/m;
    Bn(kk*(j-1)+1:kk*j,kk*(j-1)+1:kk*j)=cov(mu);
    V(kk*(j-1)+1:kk*j,kk*(j-1)+1:kk*j)=(n-1)*Wtemp/m/n+(1+1/m)*cov(mu);
    for l=1:kk
        Vi(l,j)=sqrt(V(kk*(j-1)+l,kk*(j-1)+l));
        Wi(l,j)=sqrt(W(kk*(j-1)+l,kk*(j-1)+l));
        Ri(l,j)=Vi(l,j)/Wi(l,j);
    end
    axi(j,1)=b*j;
end

figure
for i=1:5
    subplot(5,2,2*i-1), plot(axi,Ri(i,:)','-m'), title('Ri');
    subplot(5,2,2*i), plot(axi,Vi(i,:)','-g',axi,Wi(i,:)','-m'), legend('Vi','Wi'),
    title('Between and Within variances');
end
figure
for i=6:kk
    subplot(6,2,2*(i-5)-1), plot(axi,Ri(i,:)','-m'), title('Ri');
    subplot(6,2,2*(i-5)), plot(axi,Vi(i,:)','-g',axi,Wi(i,:)','-m'), legend('Vi','Wi'),
    title('Between and Within variances');
end